package com.qiu.greened.ui.main

import android.content.Intent
import android.os.Bundle
import android.view.*
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.LinearLayoutManager
import com.qiu.greened.R
import com.qiu.greened.adapter.PostAdapter
import com.qiu.greened.adapter.PostAdapter2
import com.qiu.greened.databinding.FragmentHomeBinding
import com.qiu.greened.ui.post.PostAddActivity
import com.qiu.greened.utils.showToast
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class HomeFragment : Fragment() {

    private val viewModel: HomeViewModel by viewModels()
    private var _binding: FragmentHomeBinding? = null
    private val binding get() = _binding!!
    private val postAdapter by lazy { PostAdapter() }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        val root: View = binding.root
        setHasOptionsMenu(true)
        initView()
        return root
    }

    private fun initView() {
        binding.recyclerView.layoutManager = LinearLayoutManager(context)
        binding.recyclerView.adapter = postAdapter
        //绑定数据源
        lifecycleScope.launch {
            viewModel.getPagingData().collect { pagingData ->
                postAdapter.submitData(pagingData)
            }
        }

        postAdapter.addLoadStateListener {
            binding.swipeRefresh.isRefreshing = it.prepend is LoadState.Loading
            when (it.refresh) {
                is LoadState.NotLoading -> {
                    binding.progressBar.visibility = View.INVISIBLE
                    binding.recyclerView.visibility = View.VISIBLE
                }
                is LoadState.Loading -> {
                    binding.progressBar.visibility = View.VISIBLE
                    binding.recyclerView.visibility = View.INVISIBLE
                }
                is LoadState.Error -> {
                    val state = it.refresh as LoadState.Error
                    binding.progressBar.visibility = View.INVISIBLE
                    Toast.makeText(
                        activity, "Load Error: ${state.error.message}", Toast.LENGTH_SHORT
                    ).show()
                }
            }
        }
        //设置下拉刷新
        var hasRefreshing = false
        binding.swipeRefresh.setOnRefreshListener {
            hasRefreshing = true
            postAdapter.refresh()
        }
        postAdapter.addOnPagesUpdatedListener {
            if (hasRefreshing) {
                binding.recyclerView.scrollToPosition(0)
                hasRefreshing = false
            }
        }
    }


    //菜单
    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, inflater)
        inflater.inflate(R.menu.post_list_menu, menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.add) {
            startActivity(Intent(context, PostAddActivity::class.java))
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onResume() {
        super.onResume()
        activity?.title = "Greened"
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}